package com.yan.intercepter;

import com.baomidou.kisso.SSOConfig;
import com.baomidou.kisso.SSOHelper;
import com.baomidou.kisso.Token;
import com.baomidou.kisso.web.interceptor.KissoAbstractInterceptor;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by Administrator on 2016/12/26 0026.
 *
 * http://blog.csdn.net/dutchcat/article/details/53888774
 */
public class SSOJFinalInterceptor extends KissoAbstractInterceptor implements
        Interceptor {
    private static final Logger log = LoggerFactory
            .getLogger(SSOJFinalInterceptor.class);

    public void intercept(Invocation invocation) {
        log.info("开始拦截!验证登陆.");
        HttpServletRequest request = invocation.getController().getRequest();
        HttpServletResponse response = invocation.getController().getResponse();
        Token token = SSOHelper.getToken(request);

        if (token == null) {
            if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
                // 处理ajax请求
                // 如果未认证返回401
                getHandlerInterceptor().preTokenIsNullAjax(request, response);
                log.info("拦截ajax请求.处理中.....");
            } else if ("APP".equals(request.getHeader("PLATFORM"))) {
                // 采用ajax处理方式
                getHandlerInterceptor().preTokenIsNullAjax(request, response);
                log.info("处理APP请求!");
            } else {
                // 普通请求
                try {
                    log.info("拒绝请求:" + request.getRequestURI());
                    SSOHelper.clearRedirectLogin(request, response);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } else {
            /*
             * 正常请求，request 设置 token 减少二次解密
			 */
            request.setAttribute(SSOConfig.SSO_TOKEN_ATTR, token);
            invocation.invoke();
        }
    }

}
